<template>
    <div class='hospital' v-loading="loading">
        <el-row v-if="!edit">
            <el-col class="row-bg" justify="end" :span="22">
                <el-button class="topBtn" type="primary" size="mini" @click="nextStep()" :disabled="!customerId">
                    下一步</el-button>
            </el-col>
        </el-row>
        <el-steps :space="200" :active="step" finish-status="success" align-center class="mb10">
            <el-step title="选择服务"></el-step>
            <el-step title="订单确认"></el-step>
        </el-steps>
        <div class="boxt mb10">
            <div class="info box mb10">
                <el-image style="width: 80px; height: 80px;border:1px solid #eee;border-radius: 50%;" :src="data.avatar">
                </el-image>
                <div class="txt">
                    <p class="mb10">老人姓名：{{data.name}}</p>
                    <p>身份证号：{{data.id_card}}</p>
                </div>
            </div>
            <div class="box">
                <p>家属信息</p>
                <el-table border v-loading="loading" :data="data.family">
                    <el-table-column label="家属姓名" align="center" prop="name" />
                    <el-table-column label="与老人关系" align="center">
                        <template slot-scope="scope">
                            <span>
                                {{selectDictLabel(elderRelative, scope.row.link_type)}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="联系电话" align="center" prop="mobile" />
                </el-table>
            </div>
        </div>
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
            <el-row>
                <template v-if="!edit">
                    <el-col :span="6">
                        <el-form-item label-width="0">
                            <p class="tit mb10">选择床位</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18" label-width="0">
                        <el-form-item>
                            <p>床位费合计：{{bedTotal}}</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="床位" prop="bed_id">
                            <el-select v-model="form.bed_id" placeholder="请选择床位" clearable size="small" filterable @change="getPrice">
                                <el-option v-for="dict in bedList" :key="dict.id" :label="dict.name" :value="dict.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="床位单价" prop="price">
                            <el-input style="width:215px;" v-model="form.price" disabled placeholder="请输入床位单价">
                                <template slot="append">元/月</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入住月数" prop="stay_length">
                            <el-input style="width:215px;" v-model="form.stay_length" @keyup.native="form.stay_length=handleNum(form.stay_length)"
                                placeholder="请输入入住月数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入住日期" prop="stay_date">
                            <el-date-picker v-model="form.stay_date" type="date" value-format="yyyy-MM-dd" placeholder="请选择入住日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="0">
                            <p class="tit mb10">餐饮膳食</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18" label-width="0">
                        <el-form-item>
                            <p>伙食费合计：{{eatTotal}}</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-col :span="8">
                            <el-form-item label="套餐单价" prop="meals_price">
                                <el-input style="width:215px;" v-model="form.meals_price" @keyup.native="form.meals_price=onInput(form.meals_price)"
                                    placeholder="请输入套餐单价">
                                    <template slot="append">元/月</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="0">
                            <p class="tit mb10">护理服务</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" label-width="0">
                        <el-form-item>
                            <p>护理费合计：{{nurseTotal}}</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="优惠金额" prop="discount_price">
                            <el-input v-model="form.discount_price" @keyup.native="form.discount_price=onInput(form.discount_price)" placeholder="请输入优惠金额">
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="护理费" prop="service_price">
                            <el-input style="width:215px;" v-model="form.service_price" @keyup.native="form.service_price=onInput(form.service_price)"
                                placeholder="请输入护理费">
                                <template slot="append">元/月</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="护理等级" prop="service_grade_id">
                            <el-select v-model="form.service_grade_id" placeholder="请选择服务等级" @change="changeValue" filterable clearable>
                                <el-option v-for="dict in levelList" :key="dict.id" :label="dict.name" :value="dict.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="护理服务" prop="serviceList">
                            <el-checkbox-group v-model="form.serviceList">
                                <el-checkbox v-for="dict in projectList" :label="Number(dict.id)" :key="dict.id"  :disabled="dict.is_select==1">
                                    {{dict.name}}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="21">
                        <el-form-item label="备注其他项目" prop="service_other_remarks">
                            <el-input v-model="form.service_other_remarks" type="textarea" rows="2" placeholder="请输入备注其他项目"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label-width="0">
                            <p class="tit mb10">其他收费</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="押金" prop="deposit_price">
                            <el-input style="width:215px;" v-model="form.deposit_price" @keyup.native="form.deposit_price=onInput(form.deposit_price)"
                                placeholder="请输入押金" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="一次性生活费" prop="living_price" label-width="120px">
                            <el-input style="width:215px;" v-model="form.living_price" @keyup.native="form.living_price=onInput(form.living_price)"
                                placeholder="请输入一次性生活费" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="24">
                        <el-form-item label-width="0">
                            <p class="tit mb10">入院费用核定周期设置</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入院费用核定天数" prop="verif_days" label-width="140px">
                            <!-- <el-input style="width:215px;" v-model="form.verif_days" @keyup.native="form.verif_days = handleNum(form.verif_days)"
                                placeholder="请输入入院费用核定天数" /> -->
                            <span>{{form.verif_days}}</span>
                        </el-form-item>
                    </el-col>
                </template>

                <template v-if="edit">
                    <el-col :span="24" class="mt10">
                        <el-form-item label-width="0">
                            <p class="tit mb10">订单总费用 （{{form.stay_date}} 至
                                {{$moment(form.stay_date).add(form.stay_length, 'month').format('YYYY-MM-DD')}}）</p>
                        </el-form-item>
                    </el-col>
                    <el-table class="mb20" border v-loading="loading" :data="totalList" show-summary :summary-method="getSummaries">
                        <el-table-column label="序号" align="center" prop="id" />
                        <el-table-column label="项目名称" align="center" prop="name" />
                        <el-table-column label="小计（元）" align="center" prop="money" />
                    </el-table>
                    <el-col :span="24" v-if="handleShow != 'detail'">
                        <el-form-item label-width="0">
                            <p class="tit mb10">上传合同</p>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" class="form-style" v-if="handleShow != 'detail'">
                        <el-form-item label="上传名单" prop="contract">
                            <el-upload class="upload-demo" ref="upload" :multiple="false" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                                action="###" :on-change="handleChange" :on-remove="handleRemove" :on-preview="handlePreview" :file-list="fileList"
                                :auto-upload="false" :limit="2">
                                <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
                            </el-upload>
                            <!-- <span class="eList">
                                <a v-for="item,index in fileList" :key="index" :href="item.url" class="link-type">{{item.name}}</a>
                            </span> -->

                        </el-form-item>
                        <!-- <a class="link-type load" href="/excel/预定协议模板.xlsx" target="_blank" download='预定协议模板'>下载预定协议</a> -->
                    </el-col>
                    <el-col class="row-bg" justify="end" :span="16" v-if="handleShow != 'detail'">
                        <el-button type="primary" size="mini" @click="preStep()" :disabled="!customerId">
                            上一步</el-button>
                        <el-button type="primary" size="mini" @click="submit(-1)" :disabled="!customerId">
                            保存暂不提交</el-button>
                        <el-button type="primary" size="mini" @click="submit(1)" :disabled="!customerId">
                            保存并提交</el-button>
                    </el-col>
                </template>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import { elderRelative } from "@/api/dictionary"
// import { getHospToRegister, setHospToRegister } from "@/api/marketing/admit"
// import { getNursbedListsAll } from "@/api/basic/bedManage"
// import { getServiceListsAll } from "@/api/basic/nursing"
// import { getServiceGradeInfo } from "@/api/basic/nursingGrade"
import {
    uploadImg
} from "@/api/common"
import throttle from 'lodash.throttle'
export default {
    name: 'hospital',
    props: {
        handleShow: {
            type: String, //add新增edit编辑
            default: ""
        },
        customerId: {
            type: String,
        }
    },
    data() {
        return {
            step: 1,
            data: {},
            loading: false,
            elderRelative: elderRelative,
            bedList: [],
            projectList: [],
            levelList: [],
            form: {
                customer_id: this.customerId,
                serviceList: [],
                verif_days: 15,
                service_ids:'',
            },
            rules: {
                bed_id: [{ required: true, message: '请选择床位', trigger: 'change' }],
                stay_length: [{ required: true, message: "请输入入住月数", trigger: "blur" }],
                stay_date: [{ required: true, message: '请选择入住日期', trigger: 'change' }],
                meals_price: [{ required: true, message: '请输入套餐单价', trigger: 'blur' }],
                service_price: [{ required: true, message: '请输入护理费', trigger: 'blur' }],
                deposit_price: [{ required: true, message: '请输入押金', trigger: 'blur' }],
                // living_price: [{ required: true, message: '请输入一次性生活费', trigger: 'blur' }],
                verif_days: [{ required: true, message: "请输入入院费用核定天数", trigger: "blur" }],
                service_grade_id: [{ required: true, message: '请选择护理等级', trigger: 'blur' }],
                // serviceList: [{ required: true, message: '请选择护理服务', trigger: 'change' }],
            },
            edit: false,
            totalList: [],
            fileList: [],
        }
    },
    computed: {
        bedTotal() {
            let sum = 0;
            if (this.form.price && this.form.stay_length) {
                sum = this.form.price * this.form.stay_length
            } else if (this.form.price && !this.form.stay_length) {
                sum = this.form.price * 1
            } else {
                sum = 0
            }
            return sum.toFixed(2);
        },
        eatTotal() {
            let sum = 0;
            if (this.form.meals_price && this.form.stay_length) {
                sum = this.form.meals_price * this.form.stay_length
            } else if (this.form.meals_price && !this.form.stay_length) {
                sum = this.form.meals_price * 1
            } else {
                sum = 0
            }
            return sum.toFixed(2);
        },
        nurseTotal() {
            let sum = 0;
            if (this.form.service_price && this.form.stay_length) {
                sum = this.form.service_price * this.form.stay_length
            } else if (this.form.service_price && !this.form.stay_length) {
                sum = this.form.service_price * 1
            } else {
                sum = 0
            }
            return sum.toFixed(2);
        },
    },
    watch: {
        "customerId"(val) {
            if (val) {
                // this.$set(this.form, "id", val)
                this.$set(this.form, "customer_id", val)
                this.getDetail()
            }
        },
    },
    created() {
        if (this.handleShow == "detail") {
            this.edit = true
            this.step = 2
        }
        let fun = [
            getNursbedListsAll({ type: 3, is_show_hide: 0 }),           
            getServiceListsAll(),
        ];
        Promise.all(fun).then(res => {
            this.bedList = res[0].data
            this.projectList = res[1].data
            this.getDetail()
        })
    },
    methods: {
        changeValue(value) {
            if (value) {
                this.form.serviceList = []
                getServiceGradeInfo({ grade_id: value }).then(res => {
                    this.projectList = res.data.lists
                    this.projectList.forEach(e => {
                        if (e.is_select == 1) {
                            this.form.serviceList.push(e.id)
                        }
                    });
                })
            }
        },
        getDetail() {
            if (this.customerId) {
                getHospToRegister({ customer_id: this.customerId }).then(res => {
                    this.data = res.data
                    this.form = { ...this.form, ...res.data.checkin }
                    this.form.service_grade_id = res.data.service_grade_id
                    this.projectList = res.data.service
                    this.$set(this.form, "living_price", 0)
                    this.levelList = res.data.service_grade
                    this.form.price = this.form.bed_id ? this.bedList.find(item => item.id == this.form.bed_id).price : null
                    if (this.form.meals_unit_price) {
                        this.$set(this.form, "meals_price", this.form.meals_unit_price)
                    }
                    if (this.form.service_total_price) {
                        this.$set(this.form, "service_price", this.form.service_total_price)
                    }
                    // if (this.form.living_expen_price) {
                    //     , "living_price", 0)
                    // }
                    if (this.form.service_ids) {
                        this.form.serviceList = this.form.service_ids.split(",")
                    }
                    if (this.handleShow == "detail") {
                        this.totalList = [
                            { id: 1, name: "床位费", money: this.form.bed_total_price },
                            { id: 2, name: "护理费", money: this.form.service_total_price },
                            { id: 3, name: "膳食费", money: this.form.meals_total_price },
                            { id: 4, name: "押金", money: this.form.deposit_price },
                            { id: 5, name: "优惠金额", money: this.form.discount_price ? "-" + this.form.discount_price : 0 }
                        ]
                    }
                })
            }
        },
        getPrice(val) {
            this.$set(this.form, "price", this.bedList.find(item => item.id == val).price)
        },
        preStep: throttle(function () {
            this.loading = true
            this.edit = false
            this.step = 1
            this.loading = false
        }, 1000, { trailing: false }),
        nextStep: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loading = true
                    this.form.service_ids = this.form.serviceList.length > 0 ? this.form.serviceList.join(",") : null
                    this.totalList = [
                        { id: 1, name: "床位费", money: this.bedTotal },
                        { id: 2, name: "护理费", money: this.nurseTotal },
                        { id: 3, name: "膳食费", money: this.eatTotal },
                        { id: 4, name: "押金", money: this.form.deposit_price },
                        { id: 5, name: "优惠金额", money: this.form.discount_price ? "-" + this.form.discount_price : 0 }
                    ]
                    this.edit = true
                    this.step = 2
                    this.loading = false
                }
            })
        }, 1000, { trailing: false }),
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index == 0) {
                    sums[index] = '合计';
                    return;
                }
                if ([2].includes(index)) {
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                                // return Math.floor((prev + curr) * 100) / 100;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] = sums[index].toFixed(2)
                    } else {
                        sums[index] = '--';
                    }

                }
            });
            return sums;
        },
        handleRemove(file, fileList) {
            this.fileList = fileList;
        },
        handleChange(file, fileList) {
            console.log(fileList, "fileList")
            if (fileList.length > 1) {
                fileList.splice(0, 1);
            }
            this.fileList = fileList;
            let formData = new FormData()
            formData.append("file", this.fileList[0].raw)
            uploadImg(formData).then(res => {
                console.log(res.data[0].fileurl, 222)
                this.form.contract = res.data[0].fileurl
            })
        },
        handlePreview(file) {
            // let URL = window.URL || window.webkitURL
            window.open(this.form.contract)
        },
        submit: throttle(function (status) {
            // status-1保存不提交1保存并提交
            this.loading = true
            this.form.status = status
            console.log(this.form.id, "++++")
            setHospToRegister(this.form).then(res => {
                this.msgSuccess("操作成功");
                if (status == 1) {
                    this.$emit('close')
                    this.$emit('load')
                }
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        }, 1000, { trailing: false }),
    }
}
</script>

<style lang='scss' scoped>
.el-steps {
    justify-content: center;
}
.boxt {
    background: #f8f8f8;
    padding: 20px 0;
    .info {
        display: flex;
        .txt {
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding-left: 20px;
        }
    }
}
p {
    font-size: 13px;
    color: #333333;
}
.tit {
    font-size: 14px;
    color: #666666;
    font-weight: 600;
    border-left: 5px solid #409eff;
    padding-left: 8px;
    height: 14px;
    line-height: 14px;
}
.row-bg {
    display: flex;
    justify-content: flex-end;
}
/deep/.el-upload-list {
    display: flex;
    flex-wrap: wrap;
    .el-upload-list__item {
        width: auto;
        margin-top: 10px;
    }
}
.eList {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    a {
        margin-right: 20px;
    }
}
/deep/.el-upload {
    border: 0;
    width: 80px;
}
/deep/.el-upload--text {
    height: 30px;
}
/deep/.form-style span {
    color: #ffffff;
}

/deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #409EFF;
    border-color: #409EFF;
}

/deep/ .el-checkbox__input.is-disabled+span.el-checkbox__label {
    color: #409EFF;
    cursor: not-allowed;
}
 
</style>
